package com.arrays.a1;

import java.util.Arrays;
/*
2022-04-08
寻找两个数组合并后的中位数4
 */
public class FindMedianSortedArrays4 {
    public static void main(String[] args) {
        int[] a = {1, 3};
        int[] b = {2, 4};

        double res;
        int[] t = new int[a.length + b.length];
        for (int i = 0; i < t.length; i++) {
            if (i < a.length) {
                t[i] = a[i];
            } else {
                t[i] = b[i - a.length];
            }
        }
        Arrays.sort(t);
        System.out.println(Arrays.toString(t));

        /*1 2 3 4
            1 2
         */

        if (t.length % 2 == 0) {
            res = (double) (t[(t.length / 2) - 1] + t[(t.length) / 2]) / 2;
        } else {
            res = (double) t[(t.length - 1) / 2];
        }

        System.out.println(res);

    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] nums;
        int m = nums1.length;
        int n = nums2.length;
        nums = new int[m + n];
        if (m == 0) {
            if (n % 2 == 0) {
                return (nums2[n / 2 - 1] + nums2[n / 2]) / 2.0;
            } else {

                return nums2[n / 2];
            }
        }
        if (n == 0) {
            if (m % 2 == 0) {
                return (nums1[m / 2 - 1] + nums1[m / 2]) / 2.0;
            } else {
                return nums1[m / 2];
            }
        }

        int count = 0;
        int i = 0, j = 0;
        while (count != (m + n)) {
            if (i == m) {
                while (j != n) {
                    nums[count++] = nums2[j++];
                }
                break;
            }
            if (j == n) {
                while (i != m) {
                    nums[count++] = nums1[i++];
                }
                break;
            }

            if (nums1[i] < nums2[j]) {
                nums[count++] = nums1[i++];
            } else {
                nums[count++] = nums2[j++];
            }
        }

        if (count % 2 == 0) {
            return (nums[count / 2 - 1] + nums[count / 2]) / 2.0;
        } else {
            return nums[count / 2];
        }
    }
}

